﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using admin.syh876.com.Code;

namespace admin.syh876.com.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Admin/Home/
        //管理员登录
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(LogOnModel model, string returnUrl)
        {
            if (string.IsNullOrEmpty(model.UserName) && string.IsNullOrEmpty(model.PassWord))
            {
                ModelState.AddModelError("", "用户名和密码不能为空");
                return View(model);
            }
            if (string.IsNullOrEmpty(model.UserName))
            {
                ModelState.AddModelError("", "用户名不能为空");
                return View(model);
            }

            #region 转换对象去除非法字符
            LogOnModel model_LogOnModel = new LogOnModel();
            model_LogOnModel.UserName = Common.StringManager.ClearStrictSql(model.UserName);
            model_LogOnModel.PassWord = Common.StringManager.ClearStrictSql(model.PassWord);
            #endregion

            AdminUser objAdminUser = LoginAdmin.GetAdminUser(model_LogOnModel);

            if (objAdminUser.LoginResult)
            {
                IdentityHelper.AdminUser = objAdminUser;
                SYH.Utils.JsHelper.Redirect(string.IsNullOrEmpty(returnUrl) ? "/admin/ProMgr/ProductList" : returnUrl);
                Response.End();
                return View();
            }
            else
            {
                ModelState.AddModelError("", "用户名或者密码错误");
                return View(model);
            }
        }

        //管理员退出
        public ActionResult LoginOut()
        {
            IdentityHelper.LoginOut();
            return RedirectToAction("Index", "Home");
        }

        //管理员修改密码
        public ActionResult ChangePassWord()
        {
            SYH.System.Model.SystemAdmin model = SYH.System.BLL.SystemAdmin.GetModel(IdentityHelper.AdminUser.ID);
            if (model == null)
            {
                model = new SYH.System.Model.SystemAdmin();
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult ChangePassWord(string oldPwd, string NewPwd)
        {
            //string oldPwd = Common.RequestHelper.GetFormString("txtOldpwd");
            //string NewPwd = Common.RequestHelper.GetFormString("txtNewpwd2");
            if (!string.IsNullOrEmpty(oldPwd) && !string.IsNullOrEmpty(NewPwd))
            {
                int result = SYH.System.BLL.SystemAdmin.UpdatePassword(IdentityHelper.AdminUser.ID, oldPwd, NewPwd);//0:旧密码不正确 1:成功 -1:失败

                if (result == 1)
                {
                    return Content("1");
                }


            }
            return Content("0");

        }


    }
}
